<template>
  <div>
    <q-form class="dialog_card column" ref="editRef" style="padding: 15px">
      <q-tabs
        v-model="tab"
        dense
        class="text-grey"
        active-color="primary"
        indicator-color="primary"
        align="justify"
        narrow-indicator
      >
        <q-tab name="mails" label="基础设置" />
        <q-tab name="alarms" label="商品详情" />
        <q-tab name="movies" label="商品属性" />
      </q-tabs>
      <q-separator />

      <q-tab-panels v-model="tab" animated>
        <q-tab-panel name="mails">
          <div class="tabsContent">
            <div class="text-h6" style="margin-bottom: 5px">基础信息</div>
            <q-separator />
            <div class="row q-col-gutter-x-md dialog_form q-pa-md">
              <div class="col-12">
                <h5><q-icon name="star" color="red" />商品名称：</h5>
                <q-input
                  lazy-rules
                  :rules="[
                    (val) => (val && val.length > 0) || '请输入角色描述',
                  ]"
                  outlined
                  dense
                  v-model="isform.nick_name"
                  type="text"
                  clearable
                  style="max-width: 500px"
                />
              </div>
              <div class="col-12">
                <h5><q-icon name="star" color="red" />分类：</h5>
                <q-select
                  outlined
                  dense
                  :rules="[(val) => (val && val !== null) || '请选择分类']"
                  v-model="isform.category_id"
                  option-value="id"
                  option-label="name"
                  :options="options"
                  emit-value
                  map-options
                  style="max-width: 250px"
                >
                  <template v-slot:no-option>
                    <q-item>
                      <q-item-section class="text-grey">
                        No results
                      </q-item-section>
                    </q-item>
                  </template>
                </q-select>
              </div>
              <div class="col-12">
                <h5><q-icon name="star" color="red" />商品类型：</h5>
                <q-select
                  outlined
                  dense
                  :rules="[(val) => (val && val !== null) || '请选择商品类型']"
                  v-model="isform.goods_type"
                  option-value="id"
                  option-label="name"
                  :options="options"
                  emit-value
                  map-options
                  style="max-width: 250px"
                >
                  <template v-slot:no-option>
                    <q-item>
                      <q-item-section class="text-grey">
                        No results
                      </q-item-section>
                    </q-item>
                  </template>
                </q-select>
              </div>
              <div class="col-12">
                <h5><q-icon name="star" color="red" />单位：</h5>
                <q-input
                  lazy-rules
                  :rules="[
                    (val) => (val && val.length > 0) || '请输入角色描述',
                  ]"
                  outlined
                  dense
                  v-model="isform.unit"
                  type="text"
                  clearable
                  style="max-width: 250px"
                />
              </div>

              <div class="col-12">
                <h5><q-icon name="star" color="red" />商品主图：</h5>
                <q-btn>
                  <el-image
                    style="width: 100px; height: 100px"
                    :src="imagePath(isform.goods_image)"
                    :preview-src-list="[imagePath(isform.goods_image)]"
                    hide-on-click-modal
                    preview-teleported
                    :initial-index="1"
                    fit="cover"
                  />
                  <yq-uploader
                    ref="yqupload"
                    @uploadedAvatar="uploadedAvatar"
                  ></yq-uploader>
                </q-btn>
                <div>
                  <q-btn
                    @click="importAvatar"
                    color="primary"
                    class="color-primary uploadBtn"
                    style="margin: 10px 0 5px 5px"
                    >点击上传</q-btn
                  >
                </div>
              </div>
            </div>

            <div class="text-h6" style="margin-bottom: 5px">价格库存</div>
            <q-separator />

            <div
              class="spece"
              v-for="(i, d) in isform.goods_spec_format"
              :key="d"
            >
              <div>规格{{ d + 1 }}：</div>
              <div class="spece_box">
                <div class="spece_input">
                  <q-input
                    outlined
                    dense
                    v-model="i.spec_name"
                    type="text"
                    style="max-width: 300px"
                  />
                  <q-btn
                    flat
                    round
                    dense
                    class="q-mx-xs"
                    color="grey"
                    icon="close"
                    @click="removeSpec(d)"
                  />
                </div>
                <div class="tag_box">
                  <el-tag
                    class="mx-1"
                    closable
                    type=""
                    v-for="(tag, tagIndex) in i.spec_value"
                    :key="tagIndex"
                    @close="tagClose(d, tagIndex)"
                    style="margin-right: 5px; margin-bottom: 5px"
                  >
                    {{ tag.value }}
                  </el-tag>
                </div>

                <div class="cursor-pointer" v-if="i.spec_name !== ''">
                  <div class="spece_value">+添加规格值</div>
                  <q-popup-edit
                    v-model="setValue"
                    @hide="setHide"
                    ref="popupedit"
                  >
                    <template v-slot="{ emitValue }">
                      <q-input
                        autofocus
                        dense
                        v-model="setValue"
                        hint="Your setValue"
                        @input="emitValue"
                      >
                        <template v-slot:after>
                          <q-btn
                            flat
                            dense
                            color="positive"
                            icon="check_circle"
                            @click.stop="setSpeceValue(d)"
                          />
                        </template>
                      </q-input>
                    </template>
                  </q-popup-edit>
                </div>
              </div>
            </div>
            <div class="q-pa-md">
              <q-btn
                class="btn_bottom color-primary"
                color="primary"
                label="添加规格"
                unelevated
                @click="addSpece"
              />
            </div>
            <div class="test">
              <q-card class="q-mt-lg q-pt-md q-pb-lg">
                <div class="q-pt-sm q-px-lg">
                  <q-table
                    table-style="max-height: 500px"
                    flat
                    square
                    bordered
                    separator="cell"
                    table-header-class="my-special-class"
                    style="border-bottom: 1px solid lightgrey"
                    :rows="isform.tableOptionsSku.columnDatas"
                    :columns="isform.tableOptionsSku.columns"
                    row-key="goods_name"
                    hide-bottom
                  >
                    <template v-slot:body="props">
                      <q-tr :props="props">
                        <q-td key="goods_name" :props="props">
                          <q-input
                            style="max-width: 80px"
                            v-if="props.row.edit"
                            v-model="props.row.goods_name"
                            dense
                            outlined
                          />
                          <span v-else>{{ props.row.goods_name }}</span>
                        </q-td>
                        <q-td key="goods_image" :props="props">
                          <q-input
                            style="max-width: 80px"
                            v-if="props.row.edit"
                            v-model="props.row.goods_image"
                            dense
                            outlined
                          />
                          <span v-else>{{ props.row.goods_image }}</span>
                        </q-td>
                        <q-td key="price" :props="props">
                          <q-input
                            style="max-width: 80px"
                            v-if="props.row.edit"
                            v-model="props.row.price"
                            dense
                            outlined
                          />
                          <span v-else>{{ props.row.price }}</span>
                        </q-td>
                        <q-td key="market_price" :props="props">
                          <q-input
                            style="max-width: 80px"
                            v-if="props.row.edit"
                            v-model="props.row.market_price"
                            dense
                            outlined
                          />
                          <span v-else>{{ props.row.market_price }}</span>
                        </q-td>
                        <q-td key="cost_price" :props="props">
                          <q-input
                            style="max-width: 80px"
                            v-if="props.row.edit"
                            v-model="props.row.cost_price"
                            dense
                            outlined
                          />
                          <span v-else>{{ props.row.cost_price }}</span>
                        </q-td>
                        <q-td key="goods_stock" :props="props">
                          <q-input
                            style="max-width: 80px"
                            v-if="props.row.edit"
                            v-model="props.row.goods_stock"
                            dense
                            outlined
                          />
                          <span v-else>{{ props.row.goods_stock }}</span>
                        </q-td>
                        <q-td key="is_free_shipping" :props="props">
                          <q-input
                            style="max-width: 80px"
                            v-if="props.row.edit"
                            v-model="props.row.is_free_shipping"
                            dense
                            outlined
                          />
                          <span v-else>{{ props.row.is_free_shipping }}</span>
                        </q-td>
                        <q-td key="unit" :props="props">
                          <q-input
                            style="max-width: 80px"
                            v-if="props.row.edit"
                            v-model="props.row.unit"
                            dense
                            outlined
                          />
                          <span v-else>{{ props.row.unit }}</span>
                        </q-td>

                        <q-td key="operation" :props="props">
                          <q-btn
                            v-if="props.row.edit"
                            color="primary"
                            unelevated
                            flat
                            dense
                            label="保存"
                            @click="save(props.row.index)"
                          />
                          <q-btn
                            v-else
                            color="primary"
                            unelevated
                            flat
                            dense
                            label="编辑"
                            @click="edit(props.row.index)"
                          />
                          <q-btn
                            class="sc-design"
                            color="primary"
                            unelevated
                            flat
                            dense
                            label="删除"
                          >
                            <q-menu
                              transition-show="jump-up"
                              transition-hide="jump-down"
                              content-class="text-center"
                              self="bottom left"
                              anchor="top left"
                              :offset="[60, 5]"
                            >
                              <div class="q-px-sm q-pt-md">
                                <q-icon
                                  name="info"
                                  color="warning"
                                  class="q-mr-sm"
                                />
                                是否要删除此行?
                              </div>
                              <div class="q-gutter-x-sm q-pt-sm q-pb-md">
                                <q-btn
                                  color="grey-6"
                                  unelevated
                                  class="no-border-radius text-body2"
                                  padding="2px sm"
                                  dense
                                  label="取消"
                                  v-close-popup
                                ></q-btn>
                                <q-btn
                                  color="primary"
                                  unelevated
                                  class="no-border-radius text-body2"
                                  padding="2px sm"
                                  dense
                                  label="确认"
                                  @click="deleteData(props.row.index)"
                                  v-close-popup
                                ></q-btn>
                              </div>
                            </q-menu>
                          </q-btn>
                        </q-td>
                      </q-tr>
                    </template>
                  </q-table>
                </div>
              </q-card>
            </div>
            <!-- <q-btn
              unelevated
              :ripple="{ color: 'info' }"
              class="q-mt-md full-width"
              style="border: 1px dashed lightgrey"
              label="新增成员"
              icon="add"
              @click="add"
            /> -->
            <div class="text-h6" style="margin-bottom: 5px; margin-top: 25px">
              配送信息
            </div>
            <q-separator />
            <div class="postage">
              <h5 style="display: inline-block">
                <q-icon name="star" color="red" />是否免邮：
              </h5>
              <q-option-group
                v-model="isform.is_free_shipping"
                style="display: inline-block"
                :options="[
                  { value: 1, label: '是' },
                  { value: 0, label: '否' },
                ]"
                color="primary"
                inline
              />
            </div>
            <div class="text-h6" style="margin-bottom: 5px">其他信息</div>
            <q-separator />
            <div class="row q-col-gutter-x-md dialog_form q-pa-md">
              <div class="col-12" style="margin-top: 5px">
                <h5><q-icon name="star" color="red" />排序：</h5>
                <q-input
                  lazy-rules
                  :rules="[(val) => (val && val > 0) || '请输入大于0的排序']"
                  outlined
                  dense
                  v-model.number="isform.goods_sort"
                  type="number"
                  style="max-width: 250px"
                />
              </div>
              <div class="col-12">
                <h5><q-icon name="star" color="red" />商品状态：</h5>
                <q-select
                  outlined
                  dense
                  :rules="[(val) => val !== null || '请选择是否免邮']"
                  v-model="isform.goods_state"
                  option-value="value"
                  option-label="label"
                  :options="[
                    { value: 0, label: '待审核' },
                    { value: 1, label: '上架' },
                    { value: 2, label: '审核不通过' },
                    { value: 3, label: '下架' },
                  ]"
                  emit-value
                  map-options
                  style="max-width: 250px"
                >
                  <template v-slot:no-option>
                    <q-item>
                      <q-item-section class="text-grey">
                        No results
                      </q-item-section>
                    </q-item>
                  </template>
                </q-select>
              </div>
            </div>
          </div>
        </q-tab-panel>

        <q-tab-panel name="alarms">
          <div class="tabsContent">
            <div class="text-h6" style="margin-bottom: 5px">商品详情</div>
            {{ isform.goods_content }}
            <tiny-mce
              v-model:id="isform.tinymceID"
              v-model:value="isform.goods_content"
              :toolbar="[
                'searchreplace bold italic alignleft aligncenter alignright forecolor fontsizeselect',
              ]"
              menubar="file edit"
              :height="450"
              upload
              @input="tinymcechange"
            />
          </div>
        </q-tab-panel>

        <q-tab-panel name="movies">1111 </q-tab-panel>
      </q-tab-panels>
    </q-form>
  </div>
</template>

<script lang="ts" setup>
import emitter from '@/components/eventbus';
import { userAdd, updateUser } from '@/api/basic';
import { useQuasar } from 'quasar';
import _ from 'lodash';

interface Props {
  form: {
    goods_name?: string; //商品名称
    category_id?: number; //分类id
    goods_type?: number; //商品类型id
    goods_image?: string; //商品主图
    goods_content?: string; //商品详情
    is_free_shipping?: number; //是否免邮
    unit?: string; //台
    goods_sort?: number; //排序
    goods_state?: any; //商品状态（0:待审核,1:上架,2:审核不通过,3:下架）
    goods_attr_format?: Array<any>; //商品属性
    goods_spec_format?: Array<any>; //商品规格
    sku?: Array<any>; //商品sku
    images?: Array<any>; //商品图片
    tableOptionsSku?: any; //商品价格库存表
  };
  useroptions: [];
}
const props = withDefaults(defineProps<Props>(), {
  form: () => ({}),
  useroptions: () => [],
});

const tab = ref('mails');
const editRef = ref();
const $q = useQuasar();
const yqupload = ref();
const popupedit = ref();
const setValue = ref('');

//接收兄弟组件传递事件
emitter.on('saveData', async () => {
  console.log('saveDatasaveData');
  IsValidate();
});

const tinymcechange = (e: any) => {
  isform.value.goods_content = e + '';
  // console.log('8888', isform.value.goods_content);
};
const tagClose = (d: any, index: any) => {
  console.log('tagClose');
  isform.value.goods_spec_format[d].spec_value.splice(index, 1);
};
const setSpeceValue = (index: any) => {
  console.log('setSpeceValue', setValue.value);
  if (setValue.value !== '') {
    isform.value.goods_spec_format[index].spec_value.push({
      value: setValue.value,
    });
  }
  for (var i = 0; i < isform.value.goods_spec_format.length; i++) {
    popupedit.value[i].hide();
  }
};
const setHide = () => {
  console.log('setHide');
  setValue.value = '';
};
const addSpece = () => {
  console.log('addSpece');
  isform.value.goods_spec_format.push({
    spec_name: '',
    spec_value: [],
  });
};
const removeSpec = (index: any) => {
  console.log('removeSpec');
  isform.value.goods_spec_format.splice(index, 1);
};

const edit = (index: any) => {
  isform.value.tableOptionsSku.columnDatas[index].edit = true;
};
const save = (index: any) => {
  isform.value.tableOptionsSku.columnDatas[index].edit = false;
};
const add = () => {
  console.log('新增');
  const columnDataTemp = _.cloneDeep(
    isform.value.tableOptionsSku.columnDataDefault
  );
  columnDataTemp.index = isform.value.tableOptionsSku.columnDatas.length;

  console.log(JSON.stringify(columnDataTemp));
  isform.value.tableOptionsSku.columnDatas.push(columnDataTemp);
};
const deleteData = (index: any) => {
  isform.value.tableOptionsSku.columnDatas.splice(index, 1);
  for (let i = 0; i < isform.value.tableOptionsSku.columnDatas.length; ++i) {
    isform.value.tableOptionsSku.columnDatas[i].index = i;
  }
};
// setTimeout(() => {
//   isform.value.goods_content = 'tinymce1111';
// }, 3000);
//表单验证
const IsValidate = () => {
  if (editRef.value) {
    editRef.value.validate().then(async function (validate: any) {
      if (validate) {
        console.log('验证通过');
        onSubmit();
      } else {
        console.log('验证不通过');
      }
    });
  }
};
//提交数据
const onSubmit = async () => {
  if (isform.value.id) {
    const res: any = await updateUser(isform.value);
    info(res);
    console.log('编辑111', res);
  } else {
    const res: any = await userAdd(isform.value);
    info(res);
    console.log('新建角色111', res);
  }
};
//信息返回
const info = (res: any) => {
  if (res.code == 200) {
    $q.notify({
      color: 'white',
      textColor: 'positive',
      icon: 'check_circle',
      position: 'top',
      message: res.msg,
    });
    emit('backList');
  }
};

//上传图片
const importAvatar = () => {
  yqupload.value.importAvatar();
  // avatarUploader.value.pickFiles();
};
const imagePath = (src: any) => {
  let path = '';
  if (src) {
    if (src.startsWith('http') || src.startsWith('https')) {
      return src;
    }
    path = `${process.env.VUE_APP_API_URL}/${src}`;
  }
  return path;
};
//上传图片回调
const uploadedAvatar = (xhr: any) => {
  console.log('图片状态回调', xhr);
  const response = JSON.parse(xhr.xhr.responseText);
  if (response.code == 200) {
    isform.value.goods_image =
      `${process.env.VUE_APP_API_URL}` + response.data.path;
    $q.notify({
      color: 'white',
      textColor: 'positive',
      icon: 'check_circle',
      position: 'top',
      message: response.msg,
    });
    console.log('图片地址:', isform.value.goods_image);
  } else {
    $q.notify({
      color: 'white',
      textColor: 'negative',
      icon: 'cancel',
      position: 'top',
      message: response.msg,
    });
  }
  console.log('上传图片完成', xhr, response);
  //清空
  yqupload.value.removeUpload();
};

const emit = defineEmits(['update:form', 'backList']);

const isform: any = computed({
  set(value: any) {
    // emit('update:form', value);
  },
  get() {
    console.log('props.form', props.form);
    return props.form;
  },
});

const options: any = computed({
  set(value: any) {
    // emit('update:form', value);
  },
  get() {
    return props.useroptions;
  },
});
</script>
<style scoped lang="scss">
.postage {
  padding: 10px 0;
  h5 {
    font-size: 14px;
    font-weight: 400;
    line-height: 2rem;
    letter-spacing: normal;
  }
}
.spece {
  display: flex;
  padding: 10px;
  .spece_box {
    display: flex;
    flex-direction: column;
    .spece_input {
      display: flex;
      align-items: center;
    }
    .tag_box {
      padding: 10px 0;
      max-width: 250px;
    }
  }
}
.spece_value {
  color: #1890ff;
  cursor: pointer;
  margin-top: 8px;
}
// ::v-deep(.q-btn:before) {
//   display: flex;
//   align-items: center;
//   justify-content: center;
// }\
::v-deep(.my-special-class) {
  height: 48px;
  background: #fafafa;
}
::v-deep(.my-special-class th) {
  font-size: 16px;
}

@media screen and (max-width: 780px) {
  .test {
    max-width: 320px;
  }
}
</style>
